package com.jerry.usbserial.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import com.jerry.usbserial.R
import kotlinx.android.synthetic.main.item_console.view.*
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by dugang on 2020/7/5.
 */
class ConsoleAdapter(private val mContext: Context) : BaseAdapter() {
    private val mInflater: LayoutInflater by lazy { LayoutInflater.from(mContext) }
    private val mList = mutableListOf<String>()
    private val mFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())

    override fun getItem(position: Int): String = mList[position]

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getCount(): Int = mList.size


    fun add(data: String) {
        mList.add("${mFormat.format(Date())} $data")
        notifyDataSetChanged()
    }

    fun getList(): List<String> = mList

    fun clear() {
        mList.clear()
        notifyDataSetChanged()
    }


    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view = convertView ?: mInflater.inflate(R.layout.item_console, parent, false)
        if (view.tag == null) view.tag = ItemViewHolder(view)
        (view.tag as ConsoleAdapter.ItemViewHolder).initData(position)
        return view
    }

    inner class ItemViewHolder(private val view: View) {
        fun initData(position: Int) {
            view.tv_content.text = getItem(position)
        }
    }
}